package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExistException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 创造
     *
     * @param dishDTO 碟形dto
     */
    @Override
    @Transactional
    public void create(DishDTO dishDTO) {
        Integer countDishName = dishMapper.countDishName(dishDTO.getName());
        if (countDishName > 0) {
            throw new DishExistException(MessageConstant.REPEAT_DISH_NAME);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.insert(flavors);
        }
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO 菜式页面查询dto
     * @return {@link PageResult}
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Dish dishQueue = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dishQueue);
        List<Dish> dishList = dishMapper.getList(dishQueue);
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 按ID删除批次
     *
     * @param ids ids
     */
    @Override
    @Transactional
    public void deleteBatchByIds(List<Long> ids) {
        Integer statusCount = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (statusCount > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        Integer setmealIdCount = setmealDishMapper.selectCountByIds(ids);
        if (setmealIdCount > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishFlavorMapper.deleteBatchByIds(ids);
        dishMapper.deleteBatchByIds(ids);
    }

    /**
     * 按id查询
     *
     * @param id id
     * @return {@link DishVO}
     */
    @Override
    public DishVO queryById(Long id) {
        Dish dish = dishMapper.selectDishById(id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectDishFlavorList(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 使现代化
     *
     * @param dishDTO 碟形dto
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        dishFlavorMapper.deleteBatchByIds(Collections.singletonList(dishDTO.getId()));
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.insert(flavors);
        }
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    @Override
    public void updateStatus(Long id,Integer status) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    @Override
    public List<DishVO> dishList(String categoryId) {
        List<Dish> dishList = dishMapper.getDishByCategoryId(categoryId);
        List<DishVO> newDishList = new ArrayList<>();
        dishList.forEach(s->{
            if (s.getStatus() != 0){
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(s,dishVO);
                dishVO.setFlavors(null);
                newDishList.add(dishVO);
            }
        });
        return newDishList;
    }

    private String getCacheKey(Long categoryId){
        return "DISH_BY_CATEGORY_ID:" + categoryId;
    }
}
